<template>
	<div class="box">
		<!-- 头部搜索模块 -->
		<headerSearch 
      :selectObj="selectObject" 
      :goSearchFc="searchClick" 
      :buttonList="buttonList"
    />
		<!-- 中间表格模块 -->
        <BaseTable
            :data="cargotableData"
            :columns="cargotableDataColumns"
            :tableHeight="tableHeight"
            :pagination="false"
            :loading="loading"
            @details="tableClick"
        ></BaseTable>

		<div class="page">
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryAll.startpage"
				:page-sizes="[10, 15, 20, 25, 30]"
				:page-size="queryAll.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalNum"
			></el-pagination>
		</div>


		<!-- 新建/编辑 -->
		<el-drawer
			:before-close="handleClose"
			:title="addEditMap[status]"
			:visible.sync="drawerInner"
			direction="rtl"
			size="70%"
      @open="openDrawer"
		>
      <detail ref="detail" :status="status" :fileList="fileList" :trustId="trustId"
        :listCompData="listCompData" :customerData="customerData" :processData="processData"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="submitInner()" size="mini">保 存</el-button>
        <el-button size="mini" @click="drawerInner = false">取消</el-button>
			</div>
		</el-drawer>

    
	</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/operationInstruction'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
import detail from './detail.vue'
export default {
  name: 'operationInstruction',
  components: {
    BaseTable,
    headerSearch,
    detail
  },
  data() {
    return {
      clickRow: {}, // 点击行
      trustId: '',
      // 搜索框显示对象
      selectObject: [
        {
          name: '指令编号',
          type: 'input',
          modelName: 'trustNo'
        },
        {
          name: '状态',
          type: 'select',
          modelName: 'status',
          selectValue: 'dictValue',
          selectLabel: 'dictLabel',
          selectData: [
            { dictLabel: '未发布', dictValue: '1' },
            { dictLabel: '审核中', dictValue: '2' },
            { dictLabel: '已发布', dictValue: '3' },
            { dictLabel: '作业中', dictValue: '4' },
            { dictLabel: '核销', dictValue: '5' }
          ]
        },
        {
          name: '组织',
          type: 'select',
          modelName: 'companyId',
          selectValue: 'companyId',
          selectLabel: 'companyName',
          selectData: []
        },
        {
          name: '作业过程',
          type: 'select',
          modelName: 'processCode',
          selectValue: 'processCode',
          selectLabel: 'processName',
          selectData: []
        },
        {
          name: '客户',
          type: 'select',
          modelName: 'customerId',
          selectValue: 'customerId',
          selectLabel: 'customerName',
          selectData: []
        }
      ],
      processData: [], // 作业过程
      listCompData: [], // 组织下拉框
      customerData: [], // 客户名称下拉框
      // header的按钮list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', click: () => this.cargoManage, permission: 'businessManagement:operationInstruction:add' },
        { label: '编辑', type: 'primary', icon: 'el-icon-edit-outline', click: () => this.editTrust, disabled: true, permission: 'businessManagement:operationInstruction:edit' },
        { label: '删除', type: 'danger', icon: 'el-icon-delete', click: () => this.deleteTrust, disabled: true, permission: 'businessManagement:operationInstruction:delete' },
        { label: '发布', type: 'success', icon: 'el-icon-document-checked', click: () => this.releaseTrust, disabled: true, permission: 'businessManagement:operationInstruction:release' }
      ],
      cargotableDataColumns: [ // table表头
        { prop: 'companyName', label: '组织', isShort: true },
        { prop: 'shipvoyageName', label: '船名航次', width: 150 },
        { prop: 'trustNo', label: '指令编号', width: 150 },
        { prop: 'processName', label: '作业过程' },
        { prop: 'customerName', label: '客户', isShort: true },
        { prop: 'cargoCategoryName', label: '货种' },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'status', label: '状态',
          render(h, params) {
            if (params.row.status === 1) {
              return h('el-tag', {
                props: {
                  size: 'mini'
                },
                domProps: {
                  innerHTML: '未发布'
                }
              })
            } else if (params.row.status === 2) {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'info'
                },
                domProps: {
                  innerHTML: '审核中'
                }
              })
            } else if (params.row.status === 3) {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'success'
                },
                domProps: {
                  innerHTML: '已发布'
                }
              })
            } else if (params.row.status === 4) {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'warning'
                },
                domProps: {
                  innerHTML: '作业中'
                }
              })
            } else if (params.row.status === 5) {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '核销'
                }
              })
            }
          }
        },
        { prop: 'planQuantity', label: '计划件数' },
        { prop: 'planTon', label: '计划重量' },
        { prop: 'planVolume', label: '计划体积' },
        { prop: 'checkQuantity', label: '核销件数' },
        { prop: 'checkTon', label: '核销重量' },
        { prop: 'checkVolume', label: '核销体积' },
        { prop: 'createdTime', label: '指令创建时间', width: 150 },
        { prop: 'createName', label: '创建人' },
        { prop: 'releaseName', label: '发布人' },
        { prop: 'releaseTime', label: '发布时间', width: 150 },
        { prop: 'checkName', label: '核销人' },
        { prop: 'checkTime', label: '核销时间', width: 150 }
      ],
      cargotableData: [], // 主列表数据
      activeName: 'first',
      status: 'add',
      addEditMap: {
        add: '新建作业指令',
        edit: '修改作业指令'
      },
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        status: '',
        trustNo: ''
      },
      totalNum: 0,
      fileList: [], // 附件list
      drawerInner: false, // 新建，编辑抽屉
      detailFormData: [] // 新建，编辑抽屉form表单
    }
  },
  computed: {
    tableHeight: function() {
      return this.$store.state.tableHeight - 40
    }
  },
  mounted() {
    this.getCompList()
    this.getCustomer()
    this.getProcessList()
  },
  methods: {
    /**
     * 获取作业指令
     */
    async getOperationList() {
      this.loading = true
      await api
        .reqGetOperation(this.queryAll)
        .then(res => {
          this.loading = false
          this.buttonList[1].disabled = true
          this.buttonList[2].disabled = true
          this.buttonList[3].disabled = true
          this.cargotableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
        })
        .catch(() => {})
    },
    /**
     * 新建作业指令，打开drawer
     */
    cargoManage() {
      this.drawerInner = true
      this.status = 'add'
      this.trustId = ''
      this.$nextTick(() => {
        this.$refs.detail.source = '1' // 新建默认源是船，显示船舶信息
        this.$refs.detail.formData.customerName = []
        this.$refs.detail.formData.customerId = []
        this.detailFormData = JSON.parse(JSON.stringify(this.$refs.detail.formData))
      })
    },
    /**
     * 新增/修改保存 根据是否有trustNo来判断
     */
    async submitInner() {
      const form = JSON.parse(JSON.stringify(this.$refs.detail.formData))
      form.customerName = form.customerName.join()
      form.customerId = form.customerId.join()
      form.billList = JSON.parse(JSON.stringify(this.$refs.detail.billList))
      form.billBoxList = JSON.parse(JSON.stringify(this.$refs.detail.billBoxList))
      this.$refs.detail.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!form.companyId) {
            this.$message.warning('请选择组织！')
            return
          } else if (!form.shipvoyageId && (this.$refs.detail.source === '1' || this.$refs.detail.destination === '1')) { // 只要有船名航次就要控制
            this.$message.warning('请选择船名航次！')
            return
          } else if (form.billList.length === 0 && this.$refs.detail.destination !== '5') {
            this.$message.warning('请填写提单信息！')
            return
          } else if (this.$refs.detail.source === '4' && this.$refs.detail.destination === '3') { // 集装箱信息必填,控制必填项
            let num = 0
            if (form.billBoxList.length === 0) {
              this.$message.warning('请填写集装箱信息！')
              num++
              return
            }
            form.billList.forEach(item => { // 箱-场，提单信息中的提单号必填
              if (item.billNo === '' || item.cargoAgentId === '' || item.cargoCode === '' || item.cargoOwnerId === '' || item.issuingCompanyId === '' || item.packing === '') {
                this.$message.warning('请完善提单信息！')
                num++
                return
              }
            })
            if (num > 0) return // 只弹一个提示
            form.billBoxList.forEach(item => { // 控制必填项
              if (item.boxNo === '' || item.boxType === '' || item.boxSize === '' || item.section === '' || item.quantity === '' || (item.volume === '' && form.cargoCategoryCode.slice(0, 4) === '0700') || (item.ton === '' && form.cargoCategoryCode.slice(0, 4) !== '0700')) {
                this.$message.warning('请完善集装箱信息！')
                num++
                return
              } else if (!Number.isInteger(Number(item.section))) {
                this.$message.warning('节数请添加整数！')
                num++
                return
              }
            })
            if (num > 0) return
          } else if (this.$refs.detail.source !== '1' && this.$refs.detail.source !== '3' && this.$refs.detail.destination !== '1') { // 需自行添加部分，控制必填项
            let num = 0
            form.billList.forEach(item => {
              if (item.cargoAgentId === '' || item.cargoCode === '' || item.cargoOwnerId === '' || item.issuingCompanyId === '' || item.packing === '') {
                this.$message.warning('请完善提单信息！')
                num++
                return
              }
            })
            if (num > 0) return
          } else if (this.$refs.detail.source === '3') { // 选择票货部分，控制货权剩余量。
            let num = 0
            form.billList.forEach(item => {
              if (item.cargoCode.slice(0, 4) === '0700' && Number(item.volume) > item.cargoRightsQuantity) {
                this.$message.warning(`发货体积 ${item.volume} 大于货权剩余量 ${item.cargoRightsQuantity}`)
                num++
                return
              } else if (Number(item.volume) === 0 || item.volume === '') {
                this.$message.warning('发货体积不能为0！')
                num++
                return
              }
              if (item.cargoCode.slice(0, 4) !== '0700' && Number(item.ton) > item.cargoRightsQuantity) {
                this.$message.warning(`发货重量 ${item.ton} 大于货权剩余量 ${item.cargoRightsQuantity}`)
                num++
                return
              } else if (Number(item.ton) === 0 || item.ton === '') {
                this.$message.warning('发货重量不能为0！')
                num++
                return
              }
            })
            if (num > 0) return
          }
          if (form.trustNo) { // 修改
            api.reqUpdateTrust(form).then(res => {
              if (res.data.code === '0000') {
                this.$message.success('修改成功')
                this.drawerInner = false
                this.resetDetailForm()
                this.getOperationList()
              }
            })
          } else { // 新建
            api.reqAddTrust(form).then(res => {
              if (res.data.code === '0000') {
                this.$message.success('新增成功')
                this.drawerInner = false
                this.resetDetailForm()
                this.getOperationList()
              }
            })
          }
        } else {
          this.$message.warning('请完善表单信息！')
          return false;
        }
      });
    },
    /**
     * form表单重置
     */
    resetDetailForm() {
      this.$refs.detail.$refs.ruleForm.resetFields()
      this.$bus.$emit('resetFileList')
      this.$refs.detail.formData.companyId = ''
      this.$refs.detail.formData.shipvoyageId = ''
      this.$refs.detail.formData.status = ''
      this.$refs.detail.billList = []
      this.$refs.detail.billBoxList = []
      if (this.$refs.detail.$refs.shipRuleForm) this.$refs.detail.$refs.shipRuleForm.resetFields()
      this.$refs.detail.billList = []
    },
    /**
     * 修改编辑查询
     */
    async editTrust() {
      const res = await api.reqEditTrust(this.clickRow.id)
      this.trustId = this.clickRow.id
      this.drawerInner = true
      this.status = 'edit'
      this.$nextTick(() => {
        this.resetDetailForm()
        this.$refs.detail.source = res.data.data.source
        this.$refs.detail.destination = res.data.data.destination
        this.$refs.detail.formData = res.data.data
        this.$refs.detail.billList = res.data.data.billList
        this.$refs.detail.billBoxList = res.data.data.billBoxList
        this.$refs.detail.shipFormData.id = res.data.data.shipvoyageId
        this.$refs.detail.formData.customerName = res.data.data.customerName.split(',')
        this.$refs.detail.formData.customerId = res.data.data.customerId.split(',')
        this.detailFormData = JSON.parse(JSON.stringify(this.$refs.detail.formData))
        this.fileList = res.data.data.mattachmentInfoList.map(item => {
          item.name = item.fileName
          item.fileFormat = item.fileName.split('.')[1]
          return item
        })
      })
      console.log(res, 'sss');
    },
    /**
     * 删除作业指令
     */
    async deleteTrust() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDeleteTrust(this.clickRow.id).then(res => {
          if (res.data.code === '0000') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getOperationList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /**
     * 获取点击行数据,获取船舶动态
     */
    async tableClick(row) {
      this.clickRow = JSON.parse(JSON.stringify(row))
      if (this.clickRow.status === 1) {
        this.buttonList[1].disabled = false
        this.buttonList[2].disabled = false
        this.buttonList[3].disabled = false
      } else {
        this.buttonList[1].disabled = true
        this.buttonList[2].disabled = true
        this.buttonList[3].disabled = true
      }
    },
    /**
     * 发布作业指令
     */
    async releaseTrust() {
      const res = await api.reqReleaseTrust(this.clickRow.id)
      if (res.data.code === '0000') {
        this.$message.success('发布成功')
        this.getOperationList()
      }
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getOperationList()
    },
    handleAcitveClick(tab) {
      this.queryAll.startpage = 1
      this.queryAll.pagesize = 10
      this.getOperationList()
    },
    /**
     * 获取组织
     */
    async getCompList() {
      const res = await publicapi.getListComp()
      this.listCompData = res.data.data
      this.selectObject[2].selectData = this.listCompData
    },
    /**
     * 获取客户，开证公司，货主
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      this.selectObject[4].selectData = this.customerData
    },
    /**
     * 获取作业过程
     */
    async getProcessList() {
      const res = await publicapi.getlistProcess({ mainType: '1' })
      this.processData = res.data.data
      this.selectObject[3].selectData = this.processData
    },
    async handleDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.reqDelete(id).then(res => {
          if (res.data.code === '0000') {
            this.getOperationList()

            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getOperationList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getOperationList()
    },
    /**
     * 打开抽屉的回调,将对应抽屉的form表单清空
     */
    openDrawer() {
      if (this.drawerInner && this.status === 'add') { // 动态跟踪
        this.$nextTick(() => {
          this.resetDetailForm()
        })
      }
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerInner) { // 详细数据
        oldV = this.detailFormData
        newV = this.$refs.detail.formData
      }
      console.log(oldV, newV, 'cccc');
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "~@/assets/form.less";

.selectBox {
	justify-content: space-between;
	display: flex;
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-bottom: 0;
	border-left: none;
	height: 50px;
	position: relative;
	align-items: center;
	padding-left: 14px;
	padding-right: 20px;
}
.input_box {
	display: flex;
}
.page {
	background: #ffffff;
	text-align: right;
	border-radius: 0 0 4px 4px;
	padding: 5px 20px;
}
/deep/.el-tabs--border-card > .el-tabs__content {
	padding: 0 !important;
}
//抽屉底部样式
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 16px;
	border-bottom: 1px solid gainsboro;
}
.demo-drawer__footer {
	text-align: right;
	padding-right: 20px;
	border-top: 1px solid #c8cfde;
	background-color: #f5f7fa;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	line-height: 50px;
}
.box {
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-radius: 4px 4px 0 0;
	border-top: none;
}
</style>
